import 'dart:io';

import 'package:flutter/material.dart';
import 'package:gold/base/provider_widget.dart';
import 'package:gold/route/routes.dart';
import 'package:gold/route/xfg_nav.dart';
import 'package:gold/utils/res.dart';
import 'package:gold/utils/xfg_color.dart';
import 'package:gold/utils/xfg_extension.dart';
import 'package:gold/utils/xfg_size.dart';
import 'package:gold/widgets/common_widgets.dart';
import 'package:gold/widgets/http_image.dart';
import 'package:gold/widgets/xfg_text.dart';
import 'package:provider/provider.dart';

import 'rank_content_viewmodel.dart';

/// @description: 排行榜类型内容页面
/// @author tangzhentao
/// @created at 22:35 2025/2/12

/// 排行榜内容
class RankContentPage extends StatefulWidget {
  final PoolType poolType;

  const RankContentPage({super.key, required this.poolType});

  @override
  State<RankContentPage> createState() => _RankContentState();
}

class _RankContentState extends State<RankContentPage> with AutomaticKeepAliveClientMixin {

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ProviderWidget<RankContentViewmodel>(
      model: RankContentViewmodel(widget.poolType),
      onInit: (data) => data.load(),
      builder: (ctx, rank) {
        final dateDes = _formatDate(rank.pool?.startTime, rank.pool?.endTime);
        final progress = _getProgress(rank.pool?.totalAmount?? 0, rank.pool?.targetAmount?? 0);
        return Column(
          children: [
            /// 排行榜标题
            Container(
                margin: EdgeInsets.only(top: XfgSize().size6),
                alignment: Alignment.center,
                child: XfgText(rank.pool?.name?? '', fontSize: XfgSize().text24, color: XfgColor.toExchange, bold: FontWeight.bold, fontStyle: FontStyle.italic)
            ),
            /// 活动时间和规则
            Container(
              margin: EdgeInsets.only(top: XfgSize().size10),
              alignment: Alignment.center,
              child: Container(
                width: XfgSize().size36 + boundingTextSize(dateDes, style: TextStyle(fontSize: XfgSize().text14)).width,
                height: XfgSize().size26,
                alignment: Alignment.center,
                decoration: BoxDecoration(color: XfgColor.theme, borderRadius: BorderRadius.circular(XfgSize().size26)),
                child: XfgText(dateDes, fontSize: XfgSize().text14, color: XfgColor.activityRules),
              ),
            ),
            Container(
              margin: EdgeInsets.only(top: XfgSize().size10),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  GestureDetector(
                    onTap: () => XfgNav.pushNamed(Routes.rankHistory, arguments: widget.poolType),
                    child: Container(
                      width: XfgSize().size80,
                      height: XfgSize().size26,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(color: XfgColor.theme.withValues(alpha: 0.6), borderRadius: BorderRadius.horizontal(right: Radius.circular(XfgSize().size26))),
                      child: XfgText('历史记录', fontSize: XfgSize().text16, color: XfgColor.white),
                    ),
                  ),
                  GestureDetector(
                    onTap: () => XfgNav.pushNamed(Routes.rankRules),
                    child: Container(
                      width: XfgSize().size80,
                      height: XfgSize().size26,
                      alignment: Alignment.center,
                      decoration: BoxDecoration(color: XfgColor.theme.withValues(alpha: 0.6), borderRadius: BorderRadius.horizontal(left: Radius.circular(XfgSize().size26))),
                      child: XfgText('活动规则', fontSize: XfgSize().text16, color: XfgColor.white),
                    ),
                  )
                ],
              ),
            ),
            /// 奖池累计
            Container(
              margin: EdgeInsets.only(top: XfgSize().size44),
              padding: EdgeInsets.only(left: XfgSize().size24),
              width: XfgSize().size355,
              height: XfgSize().size80,
              decoration: const BoxDecoration(image: DecorationImage(image: AssetImage(Res.imagesRankPrizePool), fit: BoxFit.cover)),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    crossAxisAlignment: CrossAxisAlignment.end,
                    children: [
                      XfgText('奖池累计', fontSize: XfgSize().text20, color: XfgColor.text1, bold: FontWeight.bold),
                      SizedBox(width: XfgSize().size12),
                      XfgText('¥ ${rank.pool?.totalAmount?? '0.00'}', color: XfgColor.theme, fontSize: XfgSize().text16)
                    ],
                  ),
                  SizedBox(height: XfgSize().size14),
                  Container(
                    width: XfgSize().size236,
                    height: XfgSize().size6,
                    decoration: BoxDecoration(color: XfgColor.rankPoolBg, borderRadius: BorderRadius.circular(XfgSize().size6)),
                    alignment: Alignment.centerLeft,
                    child: Container(
                        width: XfgSize().size236 * progress,
                        height: XfgSize().size6,
                        decoration: BoxDecoration(color: XfgColor.theme, borderRadius: BorderRadius.circular(XfgSize().size6))
                    ),
                  )
                ],
              ),
            ),
            /// 排行榜
            Expanded(
              child: Container(
                margin: EdgeInsets.all(XfgSize().size10),
                child: Stack(
                  children: [
                    Container(
                      height: XfgSize().size46,
                      padding: EdgeInsets.fromLTRB(XfgSize().size12, XfgSize().size10, XfgSize().size12, 0),
                      decoration: BoxDecoration(color: XfgColor.homeTop, borderRadius: BorderRadius.circular(XfgSize().size6)),
                      alignment: Alignment.topLeft,
                      child: Builder(builder: (con) {
                        final prizeDrawTime = con.select<RankContentViewmodel, String?>((k) => k.prizeDrawTime);
                        String prizeDes;
                        if (prizeDrawTime == null) {
                          prizeDes = '已开奖';
                        } else if (prizeDrawTime.isEmpty == true) {
                          prizeDes = '距离开奖还剩 未知';
                        } else {
                          prizeDes = '距离开奖还剩 $prizeDrawTime';
                        }
                        return XfgText(prizeDes, fontSize:  XfgSize().text14, color: XfgColor.homeRealPrice, height: Platform.isIOS ? 1:null);
                      }),
                    ),
                    Align(
                      alignment: Alignment.topCenter,
                      child: Container(
                        margin: EdgeInsets.only(top: XfgSize().size34),
                        decoration: BoxDecoration(color: XfgColor.white, borderRadius: BorderRadius.circular(XfgSize().size6)),
                        child: Column(
                          children: [
                            Container(
                              decoration: BoxDecoration(color: XfgColor.red.withValues(alpha: 0.2), borderRadius: BorderRadius.vertical(top: Radius.circular(XfgSize().size6))),
                              height: XfgSize().size44,
                              child: Row(
                                children: [
                                  Expanded(flex: 3, child: Center(child: XfgText('用户', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.bold))),
                                  Expanded(flex: 1, child: Center(child: XfgText('奖励', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.bold))),
                                  Expanded(flex: 2, child: Center(child: XfgText('上榜时间', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.bold)))
                                ],
                              ),
                            ),
                            Expanded(
                                child: MediaQuery.removePadding(
                                  context: ctx, removeTop: true, removeBottom: true,
                                  child: ListView.builder(
                                    itemCount: rank.list.length,
                                    itemBuilder: (_, index) {
                                      final data = rank.list[index];
                                      final Widget numberWidget;
                                      if (index == 0) {
                                        numberWidget = Image.asset(Res.imagesRankFirst, width: XfgSize().size18, height: XfgSize().size21);
                                      } else if (index == 1 || index == 2) {
                                        numberWidget = Container(
                                          alignment: Alignment.center,
                                          padding: EdgeInsets.only(top: XfgSize().size4),
                                          decoration: const BoxDecoration(image: DecorationImage(image: AssetImage(Res.imagesRankNumber), fit: BoxFit.fill)),
                                          width: XfgSize().size16, height: XfgSize().size20,
                                          child: XfgText('${index + 1}', fontSize: XfgSize().text10, color: XfgColor.text1, height: Platform.isIOS ? 1:null),
                                        );
                                      } else {
                                        numberWidget = XfgText('${index + 1}', fontSize: XfgSize().text16, color: XfgColor.text1, bold: FontWeight.w500);
                                      }
                                      return Container(
                                        height: XfgSize().size72,
                                        decoration: BoxDecoration(border: Border(bottom: BorderSide(color: XfgColor.colorE, width: XfgSize().size0_5))),
                                        child: Row(
                                          children: [
                                            Expanded(
                                              flex: 3,
                                              child: Row(
                                                children: [
                                                  Container(
                                                    padding: EdgeInsets.only(left: XfgSize().size16),
                                                    width: XfgSize().size54,
                                                    alignment: Alignment.centerLeft,
                                                    child: numberWidget,
                                                  ),
                                                  HttpImage(data.member?.avatar, size: Size.square(XfgSize().size40), radius: BorderRadius.circular(XfgSize().size40)),
                                                  SizedBox(width: XfgSize().size8),
                                                  XfgText(data.member?.nickname?? '', fontSize: XfgSize().text14, color: XfgColor.text1D, bold: FontWeight.bold, children: [
                                                    TextSpan(text: '\n${data.member?.uid?? ''}', style: TextStyle(color: XfgColor.text1, fontWeight: FontWeight.normal))
                                                  ]),
                                                ],
                                              )
                                            ),
                                            Expanded(flex: 1, child: Center(child: XfgText('${data.rate?? 0}%', fontSize: XfgSize().text14, color: XfgColor.text1))),
                                            Expanded(
                                              flex: 2,
                                              child: Center(
                                                child: XfgText(data.updatedAt?? '',
                                                    textAlign: TextAlign.center,
                                                    fontSize: XfgSize().text14, color: XfgColor.text1,height: widget.poolType == PoolType.week || widget.poolType == PoolType.month? 1.5:1),
                                              ),
                                            )
                                          ],
                                        ),
                                      );
                                    },
                                  ),
                                )
                            )
                          ],
                        ),
                      ),
                    )
                  ],
                ),
              ),
            ),
            /// 自己数据
            Visibility(
              visible: rank.mimeRankModel != null,
              child: Container(
                margin: EdgeInsets.symmetric(horizontal: XfgSize().size10),
                padding: EdgeInsets.fromLTRB(XfgSize().size12, 0, XfgSize().size15, XfgSize().bottomBarHeight),
                height: XfgSize().size62 + XfgSize().bottomBarHeight,
                decoration: white6Decoration,
                child: Row(
                  children: [
                    Expanded(
                      child: Row(
                        children: [
                          Container(
                            padding: EdgeInsets.only(left: XfgSize().size16),
                            width: XfgSize().size54,
                            alignment: Alignment.centerLeft,
                            child: XfgText('${rank.mimeRankModel?.ranks?? '无'}名', fontSize: XfgSize().text14, color: XfgColor.text1),
                          ),
                          HttpImage(rank.mimeRankModel?.member?.avatar, size: Size.square(XfgSize().size40), radius: BorderRadius.circular(XfgSize().size40)),
                          SizedBox(width: XfgSize().size8),
                          XfgText('${rank.mimeRankModel?.member?.nickname?? ''}\n', fontSize: XfgSize().text14, color: XfgColor.text1, bold: FontWeight.bold, height: 1.2, children: [
                            TextSpan(text: rank.mimeRankModel?.member?.uid?.toString()?? '', style: TextStyle(fontWeight: FontWeight.normal))
                          ]),
                        ],
                      ),
                    ),
                    Expanded(
                      child: Center(
                        child: XfgText('距上一名还差￥', fontSize: XfgSize().text14, color: XfgColor.text1, children: [
                          TextSpan(text: rank.mimeRankModel?.diffAmount?.toStringAsFixed(2)?? '', style: TextStyle(fontWeight: FontWeight.bold, fontSize: XfgSize().text16))]),
                      ),
                    )
                  ],
                ),
              ),
            )
          ],
        );
      },
    );
  }

  /// 获取格式时间
  String _formatDate(String? start, String? end) {
    final start1 = DateTime.tryParse(start?? '');
    if (widget.poolType == PoolType.year) {
      return start1.format(formats: formatYYYYChinese);
    } else {
      final end1 = DateTime.tryParse(end?? '');
      if (start1 != null && end1 != null) {
        final formats = formatYYYYMMDDChinese;
        // if (widget.poolType == PoolType.month) {
        //   formats = formatYYYYMMChinese;
        // }
        return '${start1.format(formats: formats)}-${end1.format(formats: formats)}';
      }
    }
    return '';
  }

  /// 获取奖池进度
  double _getProgress(double current, double total) {
    if (total == 0) {
      return 0;
    }
    return current / total;
  }

  @override
  bool get wantKeepAlive => true;
}